package org.springframework.beans.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.util.Misc;

import java.lang.reflect.Method;

public class DisposableBeanAdapter implements DisposableBean {

    private String beanName;

    private Object bean;

    private String destroyMethodName;

    public DisposableBeanAdapter(String beanName, Object bean, String destroyName) {
        this.beanName = beanName;
        this.bean = bean;
        this.destroyMethodName = destroyName;
    }

    @Override
    public void destroy() throws Exception {
        if (bean instanceof DisposableBean) {
            ((DisposableBean) bean).destroy();
        }
        if (Misc.isNotEmpty(destroyMethodName)) {
            if ((bean instanceof DisposableBean) && !"destroy".equals(destroyMethodName)) {
                Method method = bean.getClass().getMethod(destroyMethodName);
                if (method == null) {
                    throw new BeansException("destroy method" + destroyMethodName + "is not exist");
                }
                method.invoke(bean);
            }
        }
    }
}
